import { useState, useEffect, useContext } from 'react';
import moment from 'moment';
import { NavBar, Tabs, List, InfiniteScroll, Toast, SwipeAction } from 'antd-mobile';
import { CheckSquareOutlined } from '@ant-design/icons';
import { useHistory, useRouteMatch } from "react-router-dom";

import AvatarImage from '../../../components/AvatarImage';
import { MySdkStoreContext } from '../../../context/index';

import { resolveMsgFormContent } from '../../../utils';
import { MsgTypeMap } from '../../../constants';

import './style.scss';

export default function() {
  const mySdkStore = useContext(MySdkStoreContext);
  const { params: { defaultActiveKey } } = useRouteMatch();
  const [messageList, setMessageList] = useState([]);
  const [pageIndex, setPageIndex] = useState(1);
  const [pagination, setPagination] = useState({});
  const [tabKey, setTabKey] = useState(defaultActiveKey);
  const history = useHistory();
  const userId = mySdkStore.mockConfig.userId;

  // 获取数据
  const getNextData = async (index: number, { changeTab } = { changeTab: false}) => {
    const apiMap = {
      'atMeMessage': 'queryAtMeMessage',
      'concernMessage': 'queryConcernMessage',
      'dealLaterMessage': 'queryDealLaterMessage',
    };
    const api = apiMap[tabKey] || 'queryAtMeMessage';
    const res = await mySdkStore.sdk[api]({ pageIndex: index, pageSize: 100, userId });
    const { current = 1, totalItemCount, totalPage, rows = [] } = res || {};
    setPageIndex(current);
    setMessageList(changeTab? rows : [...messageList, ...rows]);
    setPagination({ totalItemCount, totalPage });
  }

  useEffect(() => {
    getNextData(pageIndex, { changeTab: true });
  }, [tabKey]);

  const handleChange = (tabKey) => {
    setTabKey(tabKey);
    setPageIndex(1);
  }

  // “稍后处理”tab下点击“处理”或”全部处理“事件
  const handlePassed = async (message?: { cid: string; messageId: string}) => {
    if (!message) {
      // 全部处理
      await mySdkStore.sdk.closeAllMessageDealLater();
      Toast.show('所有消息已处理');
      setMessageList([]);
    } else {
      // 单个处理
      await mySdkStore.sdk.closeMessageDealLater({ messages: [message]});
      setMessageList(messageList.filter(item => item.id !== message.messageId));
    }
  }

  const toChatDetailPage = (cid, msgId) => {
    history.push({ pathname: `/chatDetail/${cid}`, state: { msgId }});
  }

  // 渲染”@消息“和”特别关注“信息
  const renderMessage = (item) => {
    try {
      const messageData = JSON.parse(item.content);
      let msgType = MsgTypeMap[item.templateCode]?.toLowerCase();
      if (msgType === 'strong_reminder') msgType = 'ding';
      return resolveMsgFormContent(msgType, messageData);
    } catch (e) {
      return '[自定义消息]';
    }
    // resolveMsgFormContent(messageData)
  }

  // 渲染”稍后处理“消息
  const renderLaterMessage = item => {
    const msgType = MsgTypeMap[item.messageContentType]?.toLowerCase();
    return resolveMsgFormContent(msgType, item.content);
  }

  const list = <>
  { !!messageList.length &&
      <div className="tipBar">
        最近7天的消息
        { tabKey === 'dealLaterMessage' &&
          <a className="checkBtn" onClick={() => handlePassed()}>
            <CheckSquareOutlined /> 全部已处理
          </a>
        }
      </div>
      }
      {/* <PullToRefresh
        onRefresh={() => getNextData(1)}> */}
        <List style={{ '--border-top': 0, '--border-bottom': 0 }}>
          {messageList.map(item => {
            // const content = JSON.parse(item.content);
            const listItem = <List.Item
            key={item.msgId || item.id}
            prefix={
              <AvatarImage
                src={item.from.avatarUrl}
                nickName={item.from?.nickName}
                userName={item.from?.userName}
                userId={item.from?.userId}
                style={{ borderRadius: 8 }}
                fit='cover'
                width={42}
                height={42}
              />
            }
            description={item.chatGroup}
            extra={moment(item.timestamp).format('HH:mm')}
          >
            <div className="userName">{item.sessionName}</div>
            <div className="userMessage" onClick={() => toChatDetailPage(item.cid || item.sid, item.msgId || item.id)}>{ tabKey === 'dealLaterMessage' ? renderLaterMessage(item) : renderMessage(item)}</div>
          </List.Item>;

          return tabKey === 'dealLaterMessage' ? <SwipeAction
                key={item.id}
                rightActions={[
                  {
                    key: '1',
                    text: '已处理',
                    color: 'primary',
                    onClick: () => { handlePassed({ cid: item.cid, messageId: item.id })},
                  }
                ]}
              >
                {listItem}
            </SwipeAction>
            : listItem;
          })}
        </List>
        <InfiniteScroll loadMore={() => getNextData(pageIndex + 1)} hasMore={pagination.totalPage > pagination.current} />
      {/* </PullToRefresh> */}
    </>;

  return (<div className="messageChannelPage">
    <NavBar onBack={() => history.goBack()} style={{ background: '#fff', border: 'none' }}>消息直通车</NavBar>
    <div>
      <Tabs activeKey={tabKey} onChange={handleChange} className="pageTab">
        <Tabs.Tab title='@消息' key='atMeMessage'>
          {list}
        </Tabs.Tab>
        <Tabs.Tab title='特别关注' key='concernMessage'>
          {list}
        </Tabs.Tab>
        <Tabs.Tab title='稍后处理' key='dealLaterMessage'>
          {list}
        </Tabs.Tab>
      </Tabs>
    </div>
  </div>)
}